﻿using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace FastDev
{
    public class ResUpdater : IResCheck, IResDownload
    {
        public event Action<string, float> onUpdateProcess;

        public async UniTask<List<string>> ResCheck(string remoteConfigUrl)
        {
            try
            {
                string localResConfigPath = Application.persistentDataPath + "/" + PlatformUtil.GetPlatformName() + "/" + ResConfig.fileName;

                ResConfig localResConfig = JsonConvert.DeserializeObject<ResConfig>(File.ReadAllText(localResConfigPath)); ;
                string txt = await HttpManager.Instance.GetTxt(remoteConfigUrl);
                ResConfig remoteResConfig = null;

                if (!string.IsNullOrEmpty(txt))
                    remoteResConfig = JsonConvert.DeserializeObject<ResConfig>(txt);

                List<string> needUpdateFileNames = new List<string>();
                foreach (var item in remoteResConfig.resDict)
                {
                    if (localResConfig == null || !localResConfig.resDict.ContainsKey(item.Key) || localResConfig.resDict[item.Key] != item.Value)
                    {
                        needUpdateFileNames.Add(item.Key);
                    }
                }

                return needUpdateFileNames;
            }
            catch(Exception e)
            {
                Debug.Log(e);

                return null;
            }
        }

        public async UniTask<bool> DownloadFile(string url, string savePath)
        {
            try
            {
                //开始更新
                bool result = await HttpManager.Instance.Download(url, savePath, onUpdateProcess);
                return result;
            }
            catch(Exception e)
            {
                Debug.Log(e);
                return false;
            }
        }
    }
}
